package com.py.framework.schedule;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.py.framework.common.Constants;
import com.py.framework.common.UserCacheHelper;
import com.py.framework.common.UserSingleOnline;
import com.py.framework.core.utils.SerializingUtil;

/**
 * 用户信息清除定时任务
 * @author Leegern
 * @date   2018年4月16日
 */
@Service
public class UserClearScheduler implements InitializingBean {
	
	/** 任务线程 **/
	private ScheduledExecutorService ses;

	
	/**
	 * 执行任务(周期15分钟)
	 */
	public void doExecute() {
		ses.scheduleWithFixedDelay(new Runnable() {
			@Override
			public void run() {
				List<String> invalidTokens = new ArrayList<>();
				List<String> tokens = UserSingleOnline.getAllUserToken();
				if (! CollectionUtils.isEmpty(tokens)) {
					for (String token : tokens) {
						// 判断是否是有效用户
						if (StringUtils.isNotBlank(token) && ! UserCacheHelper.isValidUser(SerializingUtil.serialize(token))) {
							invalidTokens.add(token);
						}
					}
				}
				if (! CollectionUtils.isEmpty(invalidTokens)) {
					// 清除失效的用户令牌
					UserSingleOnline.clearUserTokens(invalidTokens);
				}
			}
		}, Constants.DELAY_TIME, Constants.PERIOD_TIME, TimeUnit.SECONDS);
	}
	
	
	/*
	 * 初始化
	 * (non-Javadoc)
	 * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
	 */
	@Override
	public void afterPropertiesSet() throws Exception {
		// 创建固定大小的调度任务线程池
		this.ses = Executors.newScheduledThreadPool(Constants.NUMBER_ONE);
		// 执行任务
		doExecute();
	}
}